package com.qm.datax.helper;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.setting.Setting;
import com.qm.datax.beans.Table;
import com.qm.datax.configuration.Configuration;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Author：wangshali
 * @CreateTime：2024-12-11
 * @Description：
 * @Source:
 * @Sink:
 * @Version：v1.0
 */

public class CKHelper {
    private final List<Table> tables;

    public List<Table> getTables() {
        return tables;
    }

    public CKHelper(String url, String database, String mysqlTables) {
        tables = new ArrayList<>();

        Db db = Db.use(DSFactory.create(
                Setting.create()
                        .set("url", url)
                        .set("user", Configuration.CK_USER)
                        .set("pass", Configuration.CK_PASSWORD)
                        .set("showSql", "false")
                        .set("showParams", "false")
                        .set("sqlLevel", "info")
        ).getDataSource());

        // 获取表，如未设置，查询数据库下面所有表
        if (mysqlTables != null && !"".equals(mysqlTables)) {
            for (String mysqlTable : mysqlTables.split(",")) {
                tables.add(new Table(mysqlTable));
            }
        }
        else {
            try {
                db.findAll(Entity.create("information_schema.TABLES")
                                .set("TABLE_SCHEMA", database))
                        .forEach(entity ->
                                tables.add(new Table(entity.getStr("TABLE_NAME"))));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


        // 获取COLUMNS
        //  SELECT * FROM system.columns WHERE database = 'px_dim' AND table = 'dim_pub_calendar';
        //  SELECT * FROM INFORMATION_SCHEMA.COLUMNS  where  table_schema='px_dim'  and table_name='dim_pub_calendar';
        for (Table table : tables) {
            try {
                db.findAll(Entity.create("INFORMATION_SCHEMA.COLUMNS")
                                .set("table_schema", database)
                                .set("table_name", table.name())
                        ).stream()
                       // .sorted(Comparator.comparingInt(o -> o.getInt("ORDINAL_POSITION")))
                        .forEach(entity -> table.addColumn(
                                entity.getStr("column_name"),
                                entity.getStr("data_type")
                        ));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
